import { showMessage } from '@/components/antd-comp/message'
import { BlockEnum, NodeProps } from '@/components/workflow/types'
import { useWorkFlowStore } from '@/store/workflowStore'
import { generateUUIDv4 } from '@/util/utils'
import { CaretRightOutlined } from '@ant-design/icons'
import type { CollapseProps } from 'antd'
import { Collapse, theme } from 'antd'
import type { FC } from 'react'
import React, { useEffect, useState } from 'react'
import { INPUT_CONSTRAINTS } from '../../components/InspectData'
import { ComponentDescMap } from '../../constants'
import { useAutoSave } from '../../hooks/use-save'
import CollapseNodeComponent from '../components/CollapseNodeComponent'
import RunDrawer from '../components/RunDrawer'
import IfCont from './components/IfCont'
import IfElseHead from './components/IfElseHead'
import IfTitleCont from './components/IfTitleCont'
import { getIfElseDefaultParams } from './default'
import './index.less'

/* 选择器Panel显示 */
const IfElsePanel: FC<NodeProps> = ({ id, data }: any) => {
  const { flowVariables, setFlowVariables, removeNodesInIteration, removeNodesInIterationAllEdgs } = useWorkFlowStore()
  const { getMergedGraph } = useAutoSave()

  const { token } = theme.useToken()
  const panelStyle: React.CSSProperties = {
    marginBottom: 24,
    background: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    border: 'none'
  }

  const createCollapseItem = (key: string, label: JSX.Element, children: JSX.Element) => ({
    key,
    label,
    children,
    style: panelStyle
  })

  const [info, setInfo] = useState({ ...getIfElseDefaultParams() }) as any

  // const getSourceOptions = info => {
  //   return info.inputList
  //     ? info.inputList.filter(input => input.variable).map(input => ({ value: input.variable, label: input.variable }))
  //     : []
  // }
  const getSourceOptions = info => {
    return (info?.ifList || []).flatMap(ifItem =>
      (ifItem.inputList || [])
        .filter(input => input?.variable)
        .map(input => ({ value: input.variable, label: input.variable }))
    )
  }

  const [sourceOptions, setSourceOptions] = useState<{ value: string; label: string }[]>(getSourceOptions(info))
  // 更新 ifList
  const updateIfListItem = (index, updater) => {
    const updatedIfList = info.ifList.map((item, i) => (i === index ? updater(item) : item))
    return { ...info, ifList: updatedIfList }
  }

  // 编辑数据
  const editData = ({ inputList, index }) => {
    const updatedInfo = updateIfListItem(index, item => ({
      ...item,
      inputList
    }))
    updataInfo(updatedInfo)
  }

  // 新增 if 条件
  const addMoreIf = () => {
    if (info.ifList.length === INPUT_CONSTRAINTS.IFELSE_NODE_CONT) {
      showMessage({
        content: '分支总数限制为' + INPUT_CONSTRAINTS.IFELSE_NODE_CONT,
        type: 'warning'
      })
      return
    }
    const newIfItem = {
      inputList: [
        {
          variable: undefined,
          value: undefined,
          type: 'cite',
          value_selector: [],
          conditions: undefined,
          id: generateUUIDv4()
        }
      ],
      ifType: 'and',
      case_id: generateUUIDv4()
    }
    const updatedInfo = { ...info, ifList: [...info.ifList, newIfItem] }
    updataInfo(updatedInfo)
  }

  // 删除
  const delMoreIf = (i: number) => {
    const updatedInfo = updateIfListItem(i, () => null)
    /* 查找当前要删除连线对应edgs里的id */
    const initGraph = getMergedGraph(data.id)
    const res = initGraph.edges.findIndex(item => {
      return item?.sourceHandle === info?.ifList[i]?.case_id
    })
    if (res !== -1) {
      // removeNodesInIteration([{ ...initGraph.edges[res], type: 'remove' }])
      removeNodesInIterationAllEdgs([{ id: initGraph.edges[res].id, type: 'remove' }])
    }
    updataInfo({ ...updatedInfo, ifList: updatedInfo.ifList.filter(Boolean) })
  }

  // 修改 ifType
  const IfTypeRefre = (i: number) => {
    const updatedInfo = updateIfListItem(i, item => ({
      ...item,
      ifType: item.ifType === 'and' ? 'or' : 'and'
    }))
    updataInfo(updatedInfo)
  }

  // 更新
  const updataInfo = (obj: any) => {
    setInfo(obj)
    setFlowVariables(id, data.title, obj)
    setSourceOptions(getSourceOptions(obj))
  }

  // 溯源信息处理后再加载页面内容
  const [loadContent, setLoadContent] = useState(false)
  useEffect(() => {
    setLoadContent(true)
  }, [sourceOptions])

  /* if */
  const InputItems = ({ item, key, i }) => [
    createCollapseItem(
      key, // 确保 key 是字符串形式
      <IfTitleCont
        title="如果"
        delType="ifElse"
        ifType={item.ifType}
        ifListLength={info?.ifList?.length}
        i={i}
        delMoreIf={delMoreIf}
        IfTypeRefre={IfTypeRefre}
      />,
      <>{loadContent && <IfCont info={item} index={i} sourceOptions={sourceOptions} editData={editData} />}</>
    )
  ]

  /* else */
  const ExportationItems: CollapseProps['items'] = [
    createCollapseItem('1999', <CollapseNodeComponent title="否则"></CollapseNodeComponent>, <div></div>)
  ]

  useEffect(() => {
    if (flowVariables && flowVariables[data.id]) {
      const obj = {
        ...info,
        ...flowVariables[data.id]
      }
      setInfo(obj)
      /* 单节点运行弹窗 */
      if (flowVariables[data.id].runDrwaerHid === 1) {
        setrunDrawerHid(true)
      }
      setSourceOptions(getSourceOptions(obj))
    }
  }, [flowVariables])

  /* 运行弹窗 */
  const [runDrawerHid, setrunDrawerHid] = useState(false)

  return (
    <div className="workflow-common-panel flexCol lim_case caseOverFlowY">
      <span className="lim_title">{data.desc || ComponentDescMap[BlockEnum.IfElse]}</span>
      {/* head 条件分支添加 */}
      <IfElseHead addMoreIf={addMoreIf} />
      {/* 内容 */}
      {info?.ifList?.length > 0 &&
        info.ifList.map((item, i) => {
          return (
            <div className="lim_cardMarBot" key={item.case_id}>
              <Collapse
                bordered={false}
                defaultActiveKey={[item.case_id]}
                expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
                style={{ background: token.colorBgContainer }}
                items={InputItems({
                  item: {
                    ...item,
                    id: info.id
                  },
                  key: item.case_id,
                  i
                })}
              />
            </div>
          )
        })}
      {/* else 否则 */}
      <div className="lim_cardMarBot">
        <Collapse
          bordered={false}
          activeKey={[]}
          onChange={() => {}}
          expandIcon={() => null}
          style={{ background: token.colorBgContainer, pointerEvents: 'none' }}
          items={ExportationItems}
        />
      </div>
      {/* 运行抽屉 */}
      {runDrawerHid && <RunDrawer nodeData={info} openDef={runDrawerHid} setrunDrawerHid={setrunDrawerHid}></RunDrawer>}
    </div>
  )
}

export default React.memo(IfElsePanel)
